package Z.dailyExercise.May;

import java.util.*;

public class _692前K个高频单词 {
    public static void main(String[] args) {
        _692前K个高频单词 ts = new _692前K个高频单词();
        ts.topKFrequent(new String[]{"i", "love", "leetcode", "i", "love", "coding"},2);

    }

    /*
    借助hashmap
     */

    public List<String> topKFrequent(String[] words, int k) {
        Map<String,Integer> map = new HashMap<>();
        for (String str:words){
            map.put(str,map.getOrDefault(str,0)+1);
        }
        List<Map.Entry<String,Integer>> ls = new ArrayList<>(map.entrySet());

        Collections.sort(ls, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if (o1.getValue().equals(o2.getValue())){
                   return o1.getKey().compareTo(o2.getKey());
                }else {
                    return o2.getValue()-o1.getValue();
                }
            }
        });

        List<String> res = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            res.add(ls.get(i).getKey());


        }

        System.out.println(res);

        return res;




    }
}
